package sas

import (
	"crypto/sha512"
	"fmt"
	"io"
	"time"

	"github.com/micro-plat/lib4go/types"
)

//Sha512Sign sha512生成签名
func (n *sasClient) Sha512Sign(input types.XMap) (sign string, data types.XMap, err error) {
	input.SetValue(n.getTimespanName(), time.Now().Format("20060102150405"))
	input.SetValue(n.getEUIDName(), n.euid)
	return n.sha512Sign(input)
}

func (n *sasClient) sha512Sign(input types.XMap) (sign string, data types.XMap, err error) {
	//获取密钥
	res, err := n.SecretGet(SHA512Str)
	if err != nil {
		return
	}

	return n.sha512SignKey(input, res.Sha512Secret)
}

func (n *sasClient) sha512SignKey(input types.XMap, key string) (sign string, data types.XMap, err error) {
	raw := n.buildRaw(input, key, SHA512Str)
	sign = sha512encrypt(raw)
	input.SetValue(n.getSignName(), sign)
	data = input
	return
}

//Encrypt SHA512哈希加密
func sha512encrypt(raw string) string {
	h := sha512.New()
	io.WriteString(h, raw)
	return fmt.Sprintf("%x", h.Sum(nil))
}
